#pragma once
#include <iostream>
#include <string>
#include <cstdlib>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Err.hpp"

const static int defaultepfd = -1;
const static int gsize = 128;

class Epoller
{
public:
    Epoller() : _epfd(defaultepfd)
    {
    }

    void Create()
    {
        _epfd = epoll_create(gsize);
        if (_epfd < 0)
        {
            logMessage(Fatal, "epoll_create error, code: %d, errstring: %s", errno, strerror(errno));
            exit(EPOLL_CREATE_ERR);
        }
    }

    int Fd()
    {
        return _epfd;
    }

    bool AddModEvent(int fd, uint32_t events, int op)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = fd; // 用户数据，epoll底层不对其进行任何修改，就是为了给未来事件就绪时返回用的，告诉用户哪个fd的事件就绪
        int n = epoll_ctl(_epfd, op, fd, &ev);
        if (n < 0)
        {
            logMessage(Fatal, "epoll_ctl error, code: %d, errstring: %s", errno, strerror(errno));
            return false;
        }
        return true;
    }

    bool DelEvent(int fd)
    {
        return epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr) == 0;
    }

    int Wait(struct epoll_event *revs, int num, int timeout)
    {
        return epoll_wait(_epfd, revs, num, timeout);
    }

    void Close()
    {
        if (_epfd != defaultepfd)
        {
            close(_epfd);
        }
    }

    ~Epoller()
    {
    }

private:
    int _epfd;
};